import React from "react";
import { useSelector, useDispatch } from "react-redux";
import { Button, Avatar, Popover, List, Image, message } from "antd";
import { UserOutlined } from "@ant-design/icons";
import "./index.scss";
import { clearUserInfo, changeLoginStatus } from "@/redux/userSlice";
import { useNavigate } from "react-router-dom";
/**
 * 用户如果登录，则展示头像，否则展示 登录/注册 按钮
 */
export default function LoginAvatar(props) {
  const isLogin = useSelector((state) => state.user.isLogin);
  const userInfo = useSelector((state) => state.user.userInfo);
  const dispatch = useDispatch();
  const navigate = useNavigate();
  let loginContent = null;

  const handleClickList = (item) => {
    if (item === "个人中心") {
      navigate("/personal");
    } else {
      // 退出登录 -> 清除数据仓库 改变登录状态 -> 清除token ->返回首页
      localStorage.removeItem("token");
      dispatch(clearUserInfo());
      dispatch(changeLoginStatus(false));
      navigate("/");
      message.success("退出成功");
    }
  };

  if (isLogin) {
    // 登录了
    const content = (
      <List
        style={{ cursor: "pointer" }}
        size="large"
        dataSource={["个人中心", "退出登录"]}
        renderItem={(item) => <List.Item onClick={() => handleClickList(item)}>{item}</List.Item>}
      />
    );
    loginContent = (
      <>
        <Popover placement="bottom" content={content}>
          <Avatar
            src={<Image preview={false} src={userInfo.avatar} />}
            className="avatarContainer"
            size="large"
            icon={<UserOutlined />}
          />
        </Popover>
      </>
    );
  } else {
    // 没登录
    loginContent = (
      <>
        <Button type="primary" size="large" onClick={props.showModal}>
          登录/注册
        </Button>
      </>
    );
  }

  return <>{loginContent}</>;
}
